package smsweb.servlet;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import smsweb.client.Util;
import smsweb.server.Sms;


import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SmsPostServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 9118897434994546993L;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		DataInputStream in = new DataInputStream(
				(InputStream) req.getInputStream());
		String text = in.readUTF();
		System.out.println(text);
		
		PrintWriter out = resp.getWriter();
		out.print("100 OK");
		out.close();
		PersistenceManager pm = Util. getPMF().getPersistenceManager();
		Sms message =  Sms.parseSms(text);
		message.setIncomingMessage(true);
		message.setRead(false);
		message.setSent(false);
		long id = System.currentTimeMillis();
		Key key = KeyFactory.createKey(Sms.class.getSimpleName(), id);
		message.setKey(key);
		pm.makePersistent(message);
		pm.close();
	}

}
